package kvraft

import (
	"6.824/labrpc"
	"sync"
	"time"
)
import "crypto/rand"
import "math/big"

const TIME_OUT_COUNT_HOLDER = 3

type Clerk struct {
	servers []*labrpc.ClientEnd
	// You will have to modify this struct.

	mu        sync.Mutex
	clientId  int64
	leaderId  int
	commandId int // 唯一标识一条消息，避免重复发送导致命令重复执行
}

func nrand() int64 {
	max := big.NewInt(int64(1) << 62)
	bigx, _ := rand.Int(rand.Reader, max)
	x := bigx.Int64()
	return x
}

func MakeClerk(servers []*labrpc.ClientEnd) *Clerk {
	return &Clerk{
		mu:        sync.Mutex{},
		servers:   servers,
		leaderId:  0,
		clientId:  nrand(),
		commandId: 0,
	}
}

func (ck *Clerk) addCommandIdAndGet() int {
	ck.mu.Lock()
	defer ck.mu.Unlock()
	ck.commandId++
	return ck.commandId
}

//
// fetch the current value for a key.
// returns "" if the key does not exist.
// keeps trying forever in the face of all other errors.
//
// you can send an RPC with code like this:
// ok := ck.servers[i].Call("KVServer.Get", &args, &reply)
//
// the types of args and reply (including whether they are pointers)
// must match the declared types of the RPC handler function's
// arguments. and reply must be passed as a pointer.
//
func (ck *Clerk) Get(key string) string {
	// You will have to modify this function.
	args := GetArgs{
		CommandId: ck.addCommandIdAndGet(),
		Key:       key,
	}
	timeoutCount := 0
	for true {
		reply := CommonReply{}
		ok := ck.servers[ck.leaderId].Call("KVServer.Get", &args, &reply)

		if !ok || reply.Err == ErrTimeOut {
			timeoutCount++
			if timeoutCount == TIME_OUT_COUNT_HOLDER {
				ck.leaderId = (ck.leaderId + 1) % len(ck.servers)
				timeoutCount = 0
			} else {
				time.Sleep(10 * time.Millisecond)
			}
			continue
		}

		if reply.Err == ErrWrongLeader {
			ck.leaderId = (ck.leaderId + 1) % len(ck.servers)
		} else if reply.Err == ErrNoKey {
			return ""
		} else {
			DPrintf("Client send get command %+v to %d and get reply %+v\n", args, ck.leaderId, reply)
			return reply.Value
		}
	}
	return ""
}

//
// shared by Put and Append.
//
// you can send an RPC with code like this:
// ok := ck.servers[i].Call("KVServer.PutAppend", &args, &reply)
//
// the types of args and reply (including whether they are pointers)
// must match the declared types of the RPC handler function's
// arguments. and reply must be passed as a pointer.
//
func (ck *Clerk) PutAppend(key string, value string, op string) {
	// You will have to modify this function.
	args := PutAppendArgs{
		CommandId: ck.addCommandIdAndGet(),
		ClientId:  ck.clientId,
		Key:       key,
		Value:     value,
		Op:        op,
	}

	timeoutCount := 0

	for true {
		reply := CommonReply{}
		ok := ck.servers[ck.leaderId].Call("KVServer.PutAppend", &args, &reply)

		if !ok || reply.Err == ErrTimeOut {
			timeoutCount++
			if timeoutCount == TIME_OUT_COUNT_HOLDER {
				ck.leaderId = (ck.leaderId + 1) % len(ck.servers)
				timeoutCount = 0
			} else {
				time.Sleep(10 * time.Millisecond)
			}
			continue
		}

		if reply.Err == ErrWrongLeader {
			ck.leaderId = (ck.leaderId + 1) % len(ck.servers)
		} else {
			DPrintf("Client %d send command %+v to %d and get reply %+v\n", args.ClientId, args, ck.leaderId, reply)
			break
		}
	}
}

func (ck *Clerk) Put(key string, value string) {
	ck.PutAppend(key, value, "Put")
}
func (ck *Clerk) Append(key string, value string) {
	ck.PutAppend(key, value, "Append")
}
